<template>
   <div class="userlist">
       <h4>用户列表</h4>
       <div class="container">
            <div class="user_top">
                <div style="float:left;width:55%;">
                  <el-button type="primary"  size="small" 
                   style="margin-bottom:14px;float:left" @click="addUser()">新增用户</el-button>
                    <!-- <div style="float:right">
                        <span>所属城市:</span>
                        <el-select v-model="value8" filterable placeholder="请选择省" style="width:200px;height: 22px;margin-left:10px;">
                                <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                        </el-select> 
                        <el-select v-model="value8" filterable placeholder="请选择市" style="width:200px;height: 22px;margin-left:10px;">
                                <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                        </el-select>     
                    </div>  -->
                </div>  
                <div class="demo-input-suffix" style="display:inline-block;float:right;">
                        <el-input clearable
                            placeholder="请输入用户名或真实姓名"
                            v-model="realName" class="filter-input" style="width:300px;"
                            @keyup.enter.native="searchUser()">
                        </el-input>
                        <el-button type="primary" size="mini" icon="el-icon-search"  @click="searchUser()">搜索</el-button>
                </div>    
            </div>
            <el-table v-loading="loading" :data="data" border style="width: 100%" ref="multipleTable" stripe>
                 <el-table-column type="index"  width="80" label="序号" align="center"></el-table-column>
                 <el-table-column prop="loginName" label="所在城市" width="140" align="center"></el-table-column>
                 <el-table-column prop="loginName" label="登录账号" width="140" align="center"></el-table-column>
                 <el-table-column prop="realName" label="真实姓名" width="140" align="center">
                </el-table-column>
                <el-table-column prop="tel" label="手机号" width="180" align="center"></el-table-column>
                <el-table-column prop="roleName" label="角色" align="center"  width="140">
                </el-table-column>
                 <el-table-column  prop="state" label="状态" align="center" width="140" :formatter="formatter">
                </el-table-column>
                <el-table-column label="操作"  align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="handleEdit(  scope.row )">编辑</el-button>
                    <el-button size="mini" type="warning" @click="forbidden(scope.row.state,scope.row.id)">{{scope.row.state== 1?'禁用':'启用'}}</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete( scope.row.id )">删除</el-button>
                </template>
                </el-table-column>
            </el-table>
             <div class="pagination" v-if="total/10>2">
                <el-pagination  background  layout="prev, pager, next" :total="total" style="text-align:left;">
                </el-pagination>
           </div>
      </div>
      <!--  新增页面模态框 -->
      <el-dialog  :title="title" :visible.sync="dialogFormVisible" width="30%" top="18vh">
            <el-form :model="form" :rules="rules"   ref="ruleForm">
                <el-form-item prop="userName" label="登录账号" :label-width="formLabelWidth">
                       <el-input v-model="form.userName" auto-complete="on"></el-input>
                </el-form-item>
                <el-form-item prop="realName" label="真实姓名" :label-width="formLabelWidth">
                     <el-input v-model="form.realName" auto-complete="on"></el-input>
                </el-form-item>
                <el-form-item prop="tel" label="手机号" :label-width="formLabelWidth">
                    <el-input v-model="form.tel" auto-complete="on"></el-input>
                </el-form-item>
                <el-form-item prop="role" label="角色" :label-width="formLabelWidth">
                    <el-select v-model="form.role" placeholder="请选择新增角色" >
                        <el-option v-for="item in roleList" :key="item.id"   
                                   :label="item.label" :value="item.value1"></el-option>
                    </el-select>
                    <p style="color:red;" v-if="title=='新增用户'">初始密码为：123456</p>
                </el-form-item>
                <!-- <el-form-item prop="city" label="所在城市" :label-width="formLabelWidth">
                    <el-select v-model="value8" filterable placeholder="请选择省" style="width:100px;height: 22px;margin-left:10px;">
                                <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                        </el-select> 
                        <el-select v-model="value8" filterable placeholder="请选择市" style="width:100px;height: 22px;margin-left:10px;">
                                <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                        </el-select> 
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelSave('ruleForm')">取 消</el-button>
                <el-button type="primary" @click="saveEdit('ruleForm')">保存</el-button>
            </div>
       </el-dialog>
  </div>  
</template>

<script>
import { addUser,adminRoleList,adminList,delAdmin,updateAdmin,updateAdminStatus } from '@/request/api'
export default {
    data(){
        var checkBlank = (rule, value, callback) => {
            if (/(^\s+)|(\s+$)|\s+/g.test(value)) {
                callback(new Error('请不要输入空格'));
            }else {
                callback()
            } 
        };
        return {
           loading:true,
           data: [],
           realName:'',
           dialogFormVisible:false,  // 新增 
           delVisible:false,         // 删除
           form: {
                userName: '',
                realName:'',
                tel:'',
                role:''
           },
           rules: {
                userName: [
                    { required: true, message: '登录账号不能为空', trigger: 'blur' },
                     { validator: checkBlank, trigger: 'blur' }
                ],
                realName: [
                     { required: true, message: '真实姓名不能为空', trigger: 'change' },
                     { validator: checkBlank, trigger: 'blur' }
                ],
                tel: [
                    {  required: true, message: '手机号不能为空', trigger: 'change' },
                    { pattern:/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57]|19[89])[0-9]{8}$/, message: '手机号格式不对', trigger: 'blur'}
                  
                ],
                role: [
                    {  required: true, message: '请选择新增角色', trigger: 'change' }
                ],
                city:[
                    {required:true,message:'请选择新增角色',trigger:'change'}
                    
                ]
           },
           roleList:[
           ],
           formLabelWidth: '120px',
           title:'',
           total:0,
           userId:'',
           //可选城市
           options: [{
                value: '选项1',
                label: '黄金糕'
                }, {
                value: '选项2',
                label: '双皮奶',
                disabled: true
                }, {
                value: '选项3',
                label: '蚵仔煎'
                }, {
                value: '选项4',
                label: '龙须面'
                }, {
                value: '选项5',
                label: '北京烤鸭'
            }],
            value8: ''
           }
    },
    created(){
         this.getadminList()
    },
    methods:{
      formatter(row, column){
        return row.state == 1?'启用' :'禁用'
      },
      searchUser(){
           this.getadminList();
      },
      addUser(){
            this.dialogFormVisible = true ;
            this.title = '新增用户' 
            this.form.userName = ''
            this.form.realName = ''
            this.form.tel = ''
            this.form.role = ''
            this.getAdminRoleList();    
      },
      saveEdit(formName){
        this.$refs[formName].validate((valid) => {
              
          if (valid) {
              // 通过验证 
              var params = {
                    loginName: this.form.userName,
                    realName:this.form.realName,
                    tel:this.form.tel,
                    role:this.form.role
              }
               if(this.title == '新增用户') {
                    addUser(params).then(res => {
                        if(res.code == 1) {
                            this.dialogFormVisible = false;
                            this.$refs[formName].resetFields();
                            this.$message.success('保存成功');
                            this.getadminList();
                        }else if(res.code == 10004) {
                            this.$message.warning('用户名已存在,请重新输入用户名');
                            this.form.userName = ''
                        }else if(res.code == 10005) {
                            this.$message.warning('手机号已存在,请重新输入用户名');
                            this.form.tel = ''
                        }
                    })
               }else if(this.title == '修改用户') {
                   updateAdmin({...params,id:this.userId}).then(res => {
                       if(res.code == 1) {
                            this.dialogFormVisible = false;
                            this.$refs[formName].resetFields();
                            this.$message.success('修改用户成功');
                            this.getadminList();
                       }else if(res.code == 10004) {
                             this.$message.warning('用户名已存在,请重新输入用户名');
                             this.form.userName = ''
                       }else if(res.code == 10005) {
                            this.$message.warning('手机号已存在,请重新输入用户名');
                            this.form.tel = ''
                        }
                   })
               }
               
          } else {
                console.log('error submit!!');
                return false;
          }
        })
         
      },
      cancelSave(formName){
           this.dialogFormVisible = false;
           this.$refs[formName].resetFields();    
      },
      handleDelete(id){
          this.$confirm("此操作将永久删除, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
         }).then(()=>{
             delAdmin({
                 id:id
             }).then(res => {
                 console.log(res);
                 if(res.code ==1) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getadminList()
                 }
             })
            

         }).catch(()=>{
              this.$message({
                    type: 'info',
                    message: '已取消删除'
              });  
         }) 
      },
      deleteRow(id){
         console.log(id)
      },
      forbidden(state,id){
          let info = state == 1?'确认禁用角色？':'确认启用角色？'
          let msg = state == 1 ? '禁用成功！' : '启用成功@' 
         let cancelMsg = state == 1 ? '已取消禁用！':'已取消启用！'
        
          this.$confirm(info, {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
         }).then(()=>{
              updateAdminStatus({
                   id:id
               }).then(res => {
                    if(res.code ==1) {
                        this.getadminList();
                         this.$message({
                            type: 'success',
                            message: msg
                        }); 
                    }
              })
            
         }).catch(()=>{
              this.$message({
                    type: 'info',
                    message: cancelMsg
              });  
         }) 
      },
      handleEdit(obj){
            //   修改用户
            this.getAdminRoleList();    
            console.log(obj);
            this.title = '修改用户'
            this.userId = obj.id;
            this.form.userName = obj.loginName
            this.form.realName = obj.realName
            this.form.tel = obj.tel
            this.form.role = obj.role
            this.dialogFormVisible = true;
      },
      getAdminRoleList(){
         adminRoleList({}).then(res=> {
               this.roleList = res.data;
         })
      },
      getadminList(){
          adminList({
              pageNum:1,
              pageSize:10,
              index:this.realName
          }).then(res=> {
              this.total = res.total;
              this.data = res.rows;
              this.loading = false;
          
          })
      }

    }

 }
</script>
<style  scoped>
.userlist {
        width:100%;
        height: 100%;
}
.userlist h4 {
    line-height: 22px;
    border-left: 5px solid rgb(32, 160, 255);
    font-size:16px;
    color: #666;
    padding-left:  10px;
    font-size:18px;
    margin-bottom:20px;
}

</style>